package gui;

import dto.ObraSocialDTO;
import dto.ObraSocialPlanDTO;
import dto.PacienteDTO;
import java.awt.Color;
import java.sql.SQLException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import logic.ObraSocial;
import logic.ObraSocialPlan;
import logic.Paciente;
import logic.User;
import util.InputHelper;

/**
 *
 * @author lucifer
 */
public class PacienteGrepPanel extends javax.swing.JPanel implements Slave {

  private Master master;

  public void SetMaster(Master master) {
    this.master = master;
  }

  public void SetModeActions() {
    isCreatingPaciente = false;
    isEditingPaciente = false;
    nuevojButton.setEnabled(true);
    modificarjButton.setEnabled(true);
    setEditables(false);
    buscarjTable.setEnabled(true);
    buscarjTextField.setEnabled(true);
    cleanAll();
    buscarjTableMouseClicked(null);

    setButtons(master.GUID() == User.REGULAR);
    if (IsCreatingTurno) {
      ((JFrame) master).setTitle("Asignación de Turnos (Selección de Pacientes) - Senzu");
    } else {
      ((JFrame) master).setTitle("Pacientes - Senzu");
    }
  }

  public boolean IsCreatingTurno = false;

  private ArrayList<Integer> pIDs;
  private ArrayList<Integer> osIDs;
  private ArrayList<Integer> planIDs;

  private boolean isCreatingPaciente = false;
  private boolean isEditingPaciente = false;

  private Paciente pacienteSeleccionado;

  public PacienteGrepPanel(Master master) {
    SetMaster(master);

    initComponents();
    initCal();

    setEditables(false);
    setUpObraSocialComboBox(obraSocialjComboBox);
    setUpPlanComboBox(planObraSocialjComboBox, 0);
    preBusqueda();
  }

  public Paciente PacienteSeleccionado() {
    return pacienteSeleccionado;
  }

  private void initCal() {
    fechaNacjDateChooser.getJCalendar().getDayChooser().setDayBordersVisible(false);
    fechaNacjDateChooser.getJCalendar().getDayChooser().setDecorationBackgroundVisible(false);
    fechaNacjDateChooser.getJCalendar().getDayChooser().setDecorationBordersVisible(false);
    fechaNacjDateChooser.getJCalendar().setDecorationBackgroundVisible(false);
    fechaNacjDateChooser.getJCalendar().setDecorationBordersVisible(false);
    fechaNacjDateChooser.setMaxSelectableDate(new Date());
  }

  private void setUpObraSocialComboBox(JComboBox c) {
    ArrayList<ObraSocialDTO> dtos = null;
    try {
      dtos = ObraSocial.All();
    } catch (Exception e) {
      // no hay obras sociales registradas
      dtos = new ArrayList<>();
    }
    osIDs = new ArrayList<>();
    String[] obraSociales = new String[dtos.size()];

    for (int i = 0; i < obraSociales.length; i++) {
      osIDs.add(dtos.get(i).getId());
      obraSociales[i] = dtos.get(i).getNombre();
    }
    c.setModel(new DefaultComboBoxModel(obraSociales));
    c.setSelectedIndex(-1);
  }

  private void setUpPlanComboBox(JComboBox c, int idObraSocial) {
    ArrayList<ObraSocialPlanDTO> dtos = null;
    try {
      dtos = ObraSocialPlan.All(idObraSocial);
    } catch (Exception e) {
      // no hay planes para una obra social
      dtos = new ArrayList<>();
    }
    planIDs = new ArrayList<>();
    String[] plans = new String[dtos.size()];

    for (int i = 0; i < plans.length; i++) {
      planIDs.add(dtos.get(i).getId());
      plans[i] = dtos.get(i).getNombre();
    }
    c.setModel(new DefaultComboBoxModel(plans));
    c.setSelectedIndex(-1);
  }

  private void setEditables(boolean b) {
    dnijTextField.setEditable(b);
    nombrejTextField.setEditable(b);
    apellidojTextField.setEditable(b);
    ((JTextField)fechaNacjDateChooser.getDateEditor().getUiComponent()).setEditable(b);
    fechaNacjDateChooser.getCalendarButton().setEnabled(b);
    obraSocialjComboBox.setEnabled(b);
    planObraSocialjComboBox.setEnabled(b);
    nafiliadojTextField.setEditable(b);
    direccionjTextField.setEditable(b);
    telLineajTextField.setEditable(b);
    telCelularjTextField.setEditable(b);
    emailjTextField.setEditable(b);
    contactoNombrejTextField.setEditable(b);
    contactoApellidojTextField.setEditable(b);
    contactoTelefonojTextField.setEditable(b);
  }

  private void setButtons(boolean b) {
    nuevojButton.setEnabled(b);
    modificarjButton.setEnabled(b);
  }

  private void setAttributes(PacienteDTO p) {
    dnijTextField.setText(String.valueOf(p.getDni()));
    nombrejTextField.setText(p.getNombre());
    apellidojTextField.setText(p.getApellido());
    fechaNacjDateChooser.setDate(InputHelper.FromNewDateToOld(p.getFechaNac().atStartOfDay()));
    nafiliadojTextField.setText(String.valueOf(p.getNAfiliado()));
    direccionjTextField.setText(p.getDireccion());
    telLineajTextField.setText(p.getTelLinea());
    telCelularjTextField.setText(p.getCelular());
    emailjTextField.setText(p.getEmail());
    contactoNombrejTextField.setText(p.getContactoNombre());
    contactoApellidojTextField.setText(p.getContactoApellido());
    contactoTelefonojTextField.setText(p.getContactoTelefono());

    obraSocialjComboBox.setSelectedIndex(osIDs.indexOf(p.getIdObraSocial()));
    planObraSocialjComboBox.setSelectedIndex(planIDs.indexOf(p.getIdPlanObraSocial()));
  }

  private void cleanAll() {
    dnijTextField.setText("");
    nombrejTextField.setText("");
    apellidojTextField.setText("");
    fechaNacjDateChooser.setDate(null);
    nafiliadojTextField.setText("");
    direccionjTextField.setText("");
    telLineajTextField.setText("");
    telCelularjTextField.setText("");
    emailjTextField.setText("");
    contactoNombrejTextField.setText("");
    contactoApellidojTextField.setText("");
    contactoTelefonojTextField.setText("");

    obraSocialjComboBox.setSelectedIndex(-1);
    planObraSocialjComboBox.setSelectedIndex(-1);
  }

  private PacienteDTO userInputForPaciente() {
    int id = -1;
    // En el caso de estar editando un paciente.
    if (pacienteSeleccionado != null) {
      id = pacienteSeleccionado.getId();
    }

    String nombre = nombrejTextField.getText();
    if (InputHelper.isNonAlphabetic(nombre)) {
      JOptionPane.showMessageDialog(this, "Nombre inválido. Ingrese correctamente el nombre del paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }
    String apellido = apellidojTextField.getText();
    if (InputHelper.isNonAlphabetic(apellido)) {
      JOptionPane.showMessageDialog(this, "Apellido inválido. Ingrese correctamente el apellido del paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }
    int dni = 0;
    try {
      dni = Integer.parseInt(dnijTextField.getText());
    } catch (NumberFormatException e) {
      JOptionPane.showMessageDialog(this, "DNI inválido. Ingrese correctamente el DNI del paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }
    if (fechaNacjDateChooser.getDate() == null) {
      JOptionPane.showMessageDialog(this, "Fecha inválida. Seleccione la fecha de nacimiento del paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }
    LocalDate fechaNac = InputHelper.FromOldDateToNew(fechaNacjDateChooser.getDate()).toLocalDate();
    int idObraSocial = 0;
    int idPlanObraSocial = 0;
    int nAfiliado = 0;
    try {
      idObraSocial = osIDs.get(obraSocialjComboBox.getSelectedIndex());
    } catch (ArrayIndexOutOfBoundsException e) {
      JOptionPane.showMessageDialog(this, "Obra social inválida. Seleccione una obra social ó particular, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }
    if (idObraSocial != 0) {
      try {
        idPlanObraSocial = planIDs.get(planObraSocialjComboBox.getSelectedIndex());
      } catch (ArrayIndexOutOfBoundsException e) {
        JOptionPane.showMessageDialog(this, "Plan de la obra social inválido. Seleccione un plan de la obra social, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
        return null;
      }
      try {
        nAfiliado = Integer.parseInt(nafiliadojTextField.getText());
      } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(this, "Número de afiliado inválido. Ingrese correctamente el número de afiliado del paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
        return null;
      }
    } else {
      planObraSocialjComboBox.setSelectedIndex(0);
      nafiliadojTextField.setText("0");
    }

    String direccion = direccionjTextField.getText();
    if (InputHelper.isNonAlphanumeric(direccion)) {
      JOptionPane.showMessageDialog(this, "Dirección inválida. Ingrese correctamente la dirección del paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }

    String telLinea = telLineajTextField.getText();
    if (InputHelper.isNonValidPhone(telLinea)) {
      JOptionPane.showMessageDialog(this, "Número de teléfono de línea inválido. Ingrese correctamente el número de télefono de línea, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }
    String celular = telCelularjTextField.getText();
    if (InputHelper.isNonValidPhone(celular)) {
      JOptionPane.showMessageDialog(this, "Número de celular inválido. Ingrese correctamente el número de celular, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }
    String email = emailjTextField.getText();
    if (!InputHelper.isValidEmail(email)) {
      JOptionPane.showMessageDialog(this, "Email inválido. Ingrese correctamente el email del paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }

    String contactoNombre = contactoNombrejTextField.getText();
    if (InputHelper.isNonAlphabetic(contactoNombre)) {
      JOptionPane.showMessageDialog(this, "Nombre del contacto inválido. Ingrese correctamente el nombre del contacto, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }
    String contactoApellido = contactoApellidojTextField.getText();
    if (InputHelper.isNonAlphabetic(contactoApellido)) {
      JOptionPane.showMessageDialog(this, "Apellido del contacto inválido. Ingrese correctamente el apellido del contacto, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }
    String contactoTelefono = contactoTelefonojTextField.getText();
    if (InputHelper.isNonValidPhone(contactoTelefono)) {
      JOptionPane.showMessageDialog(this, "Número de teléfono del contacto inválido. Ingrese correctamente el número de télefono del contacto, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
      return null;
    }

    PacienteDTO p = new PacienteDTO(id, nombre, apellido, dni, fechaNac, idObraSocial, idPlanObraSocial, nAfiliado, direccion, telLinea, celular, email, contactoNombre, contactoApellido, contactoTelefono);
    return p;
  }

  // Acá **tiene** que recibir un paciente bueno si ó si.
  // Si es null es malo. Si no es null, tiene que ser bueno seguro.
  private void createNewPaciente() {
    PacienteDTO input = userInputForPaciente();

    if (input == null) {
      return;
    }

    try {
      Paciente paciente = new Paciente(input);
      paciente.SaveNew();
      pacienteSeleccionado = paciente;

      isCreatingPaciente = false;
      nuevojButton.setEnabled(true);
      modificarjButton.setEnabled(true);
      buscarjTable.setEnabled(true);
      buscarjTextField.setEnabled(true);
      setEditables(false);

      ArrayList<PacienteDTO> dtos = new ArrayList<>();
      dtos.add(Paciente.SearchByID(pacienteSeleccionado.getId()));
      JOptionPane.showMessageDialog(
        this,
        String.format("Se registró exitosamente al paciente %s %s.", pacienteSeleccionado.getNombre(), pacienteSeleccionado.getApellido()),
        "Éxito: Nuevo paciente creado",
        JOptionPane.INFORMATION_MESSAGE
      );
      updateTabla(dtos);
      buscarjTable.setRowSelectionInterval(0, 0);
      buscarjTextField.setText(Integer.toString(pacienteSeleccionado.getDni()));
    } catch (Exception e) {
      JOptionPane.showMessageDialog(this, "Datos faltantes ó incorrectos. Ingrese los datos del paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
    }
  }

  // Acá **tiene** que recibir un paciente bueno si ó si.
  // Si es null es malo. Si no es null, tiene que ser bueno seguro.
  private void editPaciente() {
    selectPacienteFromTable();

    PacienteDTO input = userInputForPaciente();

    if (input == null) {
      return;
    }

    try {
      pacienteSeleccionado = new Paciente(input);
      pacienteSeleccionado.Update();

      isEditingPaciente = false;
      nuevojButton.setEnabled(true);
      modificarjButton.setEnabled(true);
      buscarjTable.setEnabled(true);
      buscarjTextField.setEnabled(true);
      setEditables(false);

      ArrayList<PacienteDTO> dtos = new ArrayList<>();
      dtos.add(Paciente.SearchByID(pacienteSeleccionado.getId()));
      JOptionPane.showMessageDialog(
        this,
        String.format("Se actualizaron correctamente los datos del paciente %s %s.", pacienteSeleccionado.getNombre(), pacienteSeleccionado.getApellido()),
        "Éxito: Datos del paciente actualizados",
        JOptionPane.INFORMATION_MESSAGE
      );
      updateTabla(dtos);
      buscarjTable.setRowSelectionInterval(0, 0);
      buscarjTextField.setText(Integer.toString(pacienteSeleccionado.getDni()));
    } catch (Exception e) {
      JOptionPane.showMessageDialog(this, "Datos faltantes ó incorrectos. Ingrese los datos del paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
    }
  }

  private void cancelEverything() {
    int ans;
    if (isCreatingPaciente || isEditingPaciente) {
      ans = JOptionPane.showConfirmDialog(
        this,
        isCreatingPaciente ? "Desea cancelar la creación del nuevo paciente?" : "Desea cancelar las modificaciones del paciente?",
        isCreatingPaciente ? "Cancelar creación" : "Cancelar modificaciones",
        JOptionPane.YES_NO_OPTION,
        JOptionPane.QUESTION_MESSAGE
      );
      if (ans == JOptionPane.NO_OPTION) {
        return;
      }
      isCreatingPaciente = false;
      isEditingPaciente = false;
      nuevojButton.setEnabled(true);
      modificarjButton.setEnabled(true);
      buscarjTable.setEnabled(true);
      buscarjTextField.setEnabled(true);
      setEditables(false);
      cleanAll();
      buscarjTableMouseClicked(null);
    } else {

      if (master.GUID() == User.REGULAR) {
        if (!IsCreatingTurno) {
          master.ShowSlave(master.TurnoGrepPanel());
          return;
        }
        master.TurnoGrepPanel().SetPaciente(null);
        try {
          master.TurnoGrepPanel().UpdatePacienteData(); // en este caso, limpia
        } catch (SQLException e) {
          System.out.printf("?secretaria: paciente seleccionado issue\n");
        }
        master.ShowSlave(master.TurnoGrepPanel());

      } else if (master.GUID() == User.MEDICO) {
        master.HistoriaClinicaPanel().SetPaciente(null);
        try {
          master.HistoriaClinicaPanel().UpdateDatosPaciente();
        } catch (SQLException e) {
          System.out.printf("?medico: paciente seleccionado issue\n");
        }
        master.HistoriaClinicaPanel().setCamposEditables(false);
        master.ShowSlave(master.HistoriaClinicaPanel());
      }
    }
  }

  private void selectPacienteFromTable() {
    try {
      int id = pIDs.get(buscarjTable.getSelectedRow());
      pacienteSeleccionado = new Paciente(Paciente.SearchByID(id));
    } catch (Exception e) {
      JOptionPane.showMessageDialog(this, "No seleccionó ningún paciente. Seleccione un paciente, por favor.", "Atención!", JOptionPane.WARNING_MESSAGE);
    }
  }

  private void preBusqueda() {
    try {
      updateTabla(Paciente.All());
    } catch (SQLException e) {
      System.out.printf("?p:database connection failed\n");
    }
  }

  //FIXME
  private void updateTabla(ArrayList<PacienteDTO> p) {
    DefaultTableModel m = new DefaultTableModel();
    m.addColumn("DNI");
    m.addColumn("Apellido");
    m.addColumn("Nombre");

    pIDs = new ArrayList<>();
    for (int i = 0; i < p.size(); i++) {
      pIDs.add(p.get(i).getId());
      m.addRow(
        new Object[] {
          p.get(i).getDni(),
          p.get(i).getApellido(),
          p.get(i).getNombre()
        }
      );
    }
    buscarjTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    buscarjTable.setModel(m);

    DefaultTableCellRenderer left = new DefaultTableCellRenderer();
    left.setHorizontalAlignment(SwingConstants.LEFT);

    DefaultTableCellRenderer right = new DefaultTableCellRenderer();
    right.setHorizontalAlignment(SwingConstants.RIGHT);

    buscarjTable.getColumnModel().getColumn(0).setCellRenderer(right);
    buscarjTable.getColumnModel().getColumn(0).setMinWidth(96);
    buscarjTable.getColumnModel().getColumn(0).setMaxWidth(112);
    buscarjTable.getColumnModel().getColumn(1).setCellRenderer(left);
    //buscarjTable.getColumnModel().getColumn(1).setMaxWidth(192);
    buscarjTable.getColumnModel().getColumn(2).setCellRenderer(left);
    //buscarjTable.getColumnModel().getColumn(2).setMaxWidth(192);

    for (int i = 0; i < buscarjTable.getRowCount(); i++) {
      for (int j = 0; j < buscarjTable.getColumnCount(); j++) {
        buscarjTable.scrollRectToVisible(buscarjTable.getCellRect(i, j, true));
      }
    }

    buscarjTable.getColumnModel().getColumn(0).setResizable(false);
    buscarjTable.getColumnModel().getColumn(1).setResizable(false);
    buscarjTable.getColumnModel().getColumn(2).setResizable(false);
  }

  @SuppressWarnings("unchecked")
  // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
  private void initComponents() {

    buscarjLabel = new javax.swing.JLabel();
    buscarjTextField = new javax.swing.JTextField();
    buscarjScrollPane = new javax.swing.JScrollPane();
    buscarjTable = new JTable() {
      public boolean isCellEditable(int i, int j) {
        return false;
      }
    };
    nuevojButton = new javax.swing.JButton();
    aceptarjButton = new javax.swing.JButton();
    cancelarjButton = new javax.swing.JButton();
    pacientejLabel = new javax.swing.JLabel();
    dnijTextField = new javax.swing.JTextField();
    nombrejTextField = new javax.swing.JTextField();
    apellidojTextField = new javax.swing.JTextField();
    direccionjTextField = new javax.swing.JTextField();
    telLineajTextField = new javax.swing.JTextField();
    telCelularjTextField = new javax.swing.JTextField();
    emailjTextField = new javax.swing.JTextField();
    contactoEmergenciasjPanel = new javax.swing.JPanel();
    contactoNombrejTextField = new javax.swing.JTextField();
    contactoApellidojTextField = new javax.swing.JTextField();
    contactoTelefonojTextField = new javax.swing.JTextField();
    contactoNombrejLabel = new javax.swing.JLabel();
    contactoApellidojLabel = new javax.swing.JLabel();
    contactoTelefonojLabel = new javax.swing.JLabel();
    dnijLabel = new javax.swing.JLabel();
    nombrejLabel = new javax.swing.JLabel();
    apellidojLabel = new javax.swing.JLabel();
    direccionjLabel = new javax.swing.JLabel();
    telLineajLabel = new javax.swing.JLabel();
    telCelularjLabel = new javax.swing.JLabel();
    emailjLabel = new javax.swing.JLabel();
    fechaNacjDateChooser = new kalendar.calendar.JDateChooser();
    fechaNacjLabel = new javax.swing.JLabel();
    obraSocialjComboBox = new javax.swing.JComboBox();
    planObraSocialjComboBox = new javax.swing.JComboBox();
    nafiliadojLabel = new javax.swing.JLabel();
    nafiliadojTextField = new javax.swing.JTextField();
    obraSocialjLabel = new javax.swing.JLabel();
    modificarjButton = new javax.swing.JButton();

    buscarjLabel.setHorizontalAlignment(javax.swing.SwingConstants.TRAILING);
    buscarjLabel.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/search.png"))); // NOI18N
    buscarjLabel.setMaximumSize(new java.awt.Dimension(25, 27));
    buscarjLabel.setMinimumSize(new java.awt.Dimension(25, 27));
    buscarjLabel.setPreferredSize(new java.awt.Dimension(25, 27));

    buscarjTextField.setToolTipText("Se puede buscar pacientes por nombre, apellido ó DNI.");
    buscarjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        buscarjTextFieldFocusGained(evt);
      }
    });
    buscarjTextField.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyReleased(java.awt.event.KeyEvent evt) {
        buscarjTextFieldKeyReleased(evt);
      }
    });

    buscarjTable.setModel(new javax.swing.table.DefaultTableModel(
      new Object [][] {

      },
      new String [] {
        "DNI", "Apellido", "Nombre"
      }
    ) {
      Class[] types = new Class [] {
        java.lang.Integer.class, java.lang.String.class, java.lang.String.class
      };
      boolean[] canEdit = new boolean [] {
        false, false, false
      };

      public Class getColumnClass(int columnIndex) {
        return types [columnIndex];
      }

      public boolean isCellEditable(int rowIndex, int columnIndex) {
        return canEdit [columnIndex];
      }
    });
    buscarjTable.getTableHeader().setReorderingAllowed(false);
    buscarjTable.addMouseListener(new java.awt.event.MouseAdapter() {
      public void mouseClicked(java.awt.event.MouseEvent evt) {
        buscarjTableMouseClicked(evt);
      }
    });
    buscarjTable.addKeyListener(new java.awt.event.KeyAdapter() {
      public void keyReleased(java.awt.event.KeyEvent evt) {
        buscarjTableKeyReleased(evt);
      }
    });
    buscarjScrollPane.setViewportView(buscarjTable);
    if (buscarjTable.getColumnModel().getColumnCount() > 0) {
      buscarjTable.getColumnModel().getColumn(0).setResizable(false);
      buscarjTable.getColumnModel().getColumn(1).setResizable(false);
      buscarjTable.getColumnModel().getColumn(2).setResizable(false);
    }

    nuevojButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/add.png"))); // NOI18N
    nuevojButton.setText("Nuevo");
    nuevojButton.setToolTipText("Agregar un nuevo paciente en el sistema.");
    nuevojButton.setMaximumSize(new java.awt.Dimension(120, 27));
    nuevojButton.setMinimumSize(new java.awt.Dimension(120, 27));
    nuevojButton.setPreferredSize(new java.awt.Dimension(120, 27));
    nuevojButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        nuevojButtonActionPerformed(evt);
      }
    });

    aceptarjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/aceptar.png"))); // NOI18N
    aceptarjButton.setText("Aceptar");
    aceptarjButton.setMaximumSize(new java.awt.Dimension(120, 27));
    aceptarjButton.setMinimumSize(new java.awt.Dimension(120, 27));
    aceptarjButton.setPreferredSize(new java.awt.Dimension(120, 27));
    aceptarjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        aceptarjButtonActionPerformed(evt);
      }
    });

    cancelarjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/cancelar.png"))); // NOI18N
    cancelarjButton.setText("Cancelar");
    cancelarjButton.setMaximumSize(new java.awt.Dimension(120, 27));
    cancelarjButton.setMinimumSize(new java.awt.Dimension(120, 27));
    cancelarjButton.setPreferredSize(new java.awt.Dimension(120, 27));
    cancelarjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        cancelarjButtonActionPerformed(evt);
      }
    });

    pacientejLabel.setText("<html><b>Paciente</b></html>");

    dnijTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    dnijTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    dnijTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    dnijTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        dnijTextFieldFocusGained(evt);
      }
    });

    nombrejTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    nombrejTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    nombrejTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    nombrejTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        nombrejTextFieldFocusGained(evt);
      }
    });

    apellidojTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    apellidojTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    apellidojTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    apellidojTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        apellidojTextFieldFocusGained(evt);
      }
    });

    direccionjTextField.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
    direccionjTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    direccionjTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    direccionjTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    direccionjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        direccionjTextFieldFocusGained(evt);
      }
    });

    telLineajTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    telLineajTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    telLineajTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    telLineajTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        telLineajTextFieldFocusGained(evt);
      }
    });

    telCelularjTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    telCelularjTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    telCelularjTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    telCelularjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        telCelularjTextFieldFocusGained(evt);
      }
    });

    emailjTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    emailjTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    emailjTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    emailjTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        emailjTextFieldFocusGained(evt);
      }
    });

    contactoEmergenciasjPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Contacto en caso de emergencias", javax.swing.border.TitledBorder.LEFT, javax.swing.border.TitledBorder.TOP));
    contactoEmergenciasjPanel.setMaximumSize(new java.awt.Dimension(400, 136));
    contactoEmergenciasjPanel.setMinimumSize(new java.awt.Dimension(400, 136));
    contactoEmergenciasjPanel.setPreferredSize(new java.awt.Dimension(400, 136));

    contactoNombrejTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    contactoNombrejTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    contactoNombrejTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    contactoNombrejTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        contactoNombrejTextFieldFocusGained(evt);
      }
    });

    contactoApellidojTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    contactoApellidojTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    contactoApellidojTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    contactoApellidojTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        contactoApellidojTextFieldFocusGained(evt);
      }
    });

    contactoTelefonojTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    contactoTelefonojTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    contactoTelefonojTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    contactoTelefonojTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        contactoTelefonojTextFieldFocusGained(evt);
      }
    });

    contactoNombrejLabel.setText("Nombre");

    contactoApellidojLabel.setText("Apellido");

    contactoTelefonojLabel.setText("Teléfono");

    javax.swing.GroupLayout contactoEmergenciasjPanelLayout = new javax.swing.GroupLayout(contactoEmergenciasjPanel);
    contactoEmergenciasjPanel.setLayout(contactoEmergenciasjPanelLayout);
    contactoEmergenciasjPanelLayout.setHorizontalGroup(
      contactoEmergenciasjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, contactoEmergenciasjPanelLayout.createSequentialGroup()
        .addContainerGap(20, Short.MAX_VALUE)
        .addGroup(contactoEmergenciasjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(contactoNombrejLabel, javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(contactoApellidojLabel, javax.swing.GroupLayout.Alignment.TRAILING)
          .addComponent(contactoTelefonojLabel, javax.swing.GroupLayout.Alignment.TRAILING))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(contactoEmergenciasjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addComponent(contactoNombrejTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(contactoApellidojTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(contactoTelefonojTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addContainerGap())
    );
    contactoEmergenciasjPanelLayout.setVerticalGroup(
      contactoEmergenciasjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(contactoEmergenciasjPanelLayout.createSequentialGroup()
        .addContainerGap()
        .addGroup(contactoEmergenciasjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(contactoNombrejTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(contactoNombrejLabel))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(contactoEmergenciasjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(contactoApellidojTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(contactoApellidojLabel))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(contactoEmergenciasjPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
          .addComponent(contactoTelefonojTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addComponent(contactoTelefonojLabel))
        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    );

    dnijLabel.setText("DNI");

    nombrejLabel.setText("Nombre");

    apellidojLabel.setText("Apellido");

    direccionjLabel.setText("Dirección");

    telLineajLabel.setText("Teléfono de línea");

    telCelularjLabel.setText("Teléfono celular");

    emailjLabel.setText("Email");

    fechaNacjDateChooser.setDateFormatString("dd/MM/yyyy");
    fechaNacjDateChooser.setPreferredSize(new java.awt.Dimension(286, 27));

    fechaNacjLabel.setText("Fecha de nac.");

    obraSocialjComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione obra social" }));
    obraSocialjComboBox.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        obraSocialjComboBoxActionPerformed(evt);
      }
    });

    planObraSocialjComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccione Plan" }));

    nafiliadojLabel.setText("N° de Afiliado");

    nafiliadojTextField.setMaximumSize(new java.awt.Dimension(286, 27));
    nafiliadojTextField.setMinimumSize(new java.awt.Dimension(286, 27));
    nafiliadojTextField.setPreferredSize(new java.awt.Dimension(286, 27));
    nafiliadojTextField.addFocusListener(new java.awt.event.FocusAdapter() {
      public void focusGained(java.awt.event.FocusEvent evt) {
        nafiliadojTextFieldFocusGained(evt);
      }
    });

    obraSocialjLabel.setText("Obra social");

    modificarjButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/gui/modificar.png"))); // NOI18N
    modificarjButton.setText("Modificar");
    modificarjButton.setMaximumSize(new java.awt.Dimension(120, 27));
    modificarjButton.setMinimumSize(new java.awt.Dimension(120, 27));
    modificarjButton.setPreferredSize(new java.awt.Dimension(120, 27));
    modificarjButton.addActionListener(new java.awt.event.ActionListener() {
      public void actionPerformed(java.awt.event.ActionEvent evt) {
        modificarjButtonActionPerformed(evt);
      }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGap(0, 0, 0)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
          .addGroup(layout.createSequentialGroup()
            .addComponent(buscarjLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(buscarjTextField))
          .addComponent(buscarjScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        .addGap(12, 12, 12)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
          .addGroup(layout.createSequentialGroup()
            .addGap(0, 0, Short.MAX_VALUE)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addGroup(layout.createSequentialGroup()
                .addComponent(aceptarjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cancelarjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
              .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                  .addComponent(nombrejLabel)
                  .addComponent(apellidojLabel)
                  .addComponent(direccionjLabel)
                  .addComponent(telLineajLabel)
                  .addComponent(telCelularjLabel)
                  .addComponent(emailjLabel)
                  .addComponent(nafiliadojLabel)
                  .addComponent(obraSocialjLabel)
                  .addComponent(dnijLabel)
                  .addComponent(fechaNacjLabel))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                  .addGroup(layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(nuevojButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addComponent(modificarjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                  .addGroup(layout.createSequentialGroup()
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                      .addComponent(telCelularjTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addComponent(telLineajTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addComponent(nombrejTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addComponent(apellidojTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addComponent(fechaNacjDateChooser, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                      .addComponent(nafiliadojTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(obraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(planObraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 140, javax.swing.GroupLayout.PREFERRED_SIZE))
                      .addComponent(direccionjTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addComponent(dnijTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                      .addComponent(emailjTextField, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
          .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addComponent(pacientejLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(contactoEmergenciasjPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(0, 0, Short.MAX_VALUE))))
    );
    layout.setVerticalGroup(
      layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
      .addGroup(layout.createSequentialGroup()
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addComponent(buscarjLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
          .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
            .addComponent(buscarjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(nuevojButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(pacientejLabel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(modificarjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
          .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(nombrejTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(nombrejLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(apellidojTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(apellidojLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
              .addComponent(fechaNacjLabel)
              .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                  .addComponent(dnijTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                  .addComponent(dnijLabel))
                .addGap(18, 18, Short.MAX_VALUE)
                .addComponent(fechaNacjDateChooser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
            .addGap(18, 18, 18)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(planObraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(obraSocialjComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(obraSocialjLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(nafiliadojTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(nafiliadojLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(direccionjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(direccionjLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(telLineajTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(telLineajLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(telCelularjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(telCelularjLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(emailjTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(emailjLabel))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(contactoEmergenciasjPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
              .addComponent(aceptarjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
              .addComponent(cancelarjButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
          .addComponent(buscarjScrollPane)))
    );
  }// </editor-fold>//GEN-END:initComponents

  private void buscarjTextFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_buscarjTextFieldKeyReleased
    String itemToSearch =  buscarjTextField.getText();
    ArrayList<PacienteDTO> pacienteDTOs;
    try {
      pacienteDTOs = Paciente.Search(itemToSearch);
      updateTabla(pacienteDTOs);
      if (pacienteDTOs.isEmpty() || buscarjTable.getSelectedRow() == -1) {
        cleanAll();
      }
      if (pacienteDTOs.size() == 1) {
        buscarjTable.setRowSelectionInterval(0, 0);
        buscarjTableMouseClicked(null);
      }
    } catch (SQLException e) {
      JOptionPane.showMessageDialog(this, InputHelper.PanicMessage, "ERROR! Esta aplicación se cerrará", JOptionPane.ERROR_MESSAGE);
      System.exit(66);
    }
  }//GEN-LAST:event_buscarjTextFieldKeyReleased

  private void buscarjTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_buscarjTableMouseClicked
    // preinit
    int sel = buscarjTable.getSelectedRow();
    if (sel == -1 || !buscarjTable.isEnabled()) {
      return;
    }

    int id = pIDs.get(sel);
    try {
      PacienteDTO p = Paciente.SearchByID(id);
      setEditables(false);
      setAttributes(p);
    } catch (SQLException e) {
      // FIXME
      // si entra acá, hay algún problema con la DB
      System.out.printf("?id not found\n");
    }
  }//GEN-LAST:event_buscarjTableMouseClicked

  private void nuevojButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nuevojButtonActionPerformed
    isCreatingPaciente = true;
    nuevojButton.setEnabled(false);
    modificarjButton.setEnabled(false);
    buscarjTable.setEnabled(false);
    buscarjTextField.setEnabled(false);
    dnijTextField.setText("Ingrese el DNI del paciente.");
    nombrejTextField.setText("Ingrese el nombre del paciente.");
    apellidojTextField.setText("Ingrese el apellido del paciente.");
    fechaNacjDateChooser.setDate(null);
    ((JTextField)fechaNacjDateChooser.getDateEditor().getUiComponent()).setText("Seleccione la fecha");
    ((JTextField)fechaNacjDateChooser.getDateEditor().getUiComponent()).setForeground(Color.BLACK);
    nafiliadojTextField.setText("Ingrese el N° de afiliado del paciente.");
    direccionjTextField.setText("Ingrese la dirección del paciente.");
    telLineajTextField.setText("Ingrese el teléfono de linea del paciente.");
    telCelularjTextField.setText("Ingrese el teléfono celular del paciente.");
    emailjTextField.setText("Ingrese el email del paciente.");
    contactoNombrejTextField.setText("Ingrese el nombre del contacto.");
    contactoApellidojTextField.setText("Ingrese el apellido del contacto.");
    contactoTelefonojTextField.setText("Ingrese el teléfono del contacto.");
    setUpObraSocialComboBox(obraSocialjComboBox);
    setUpPlanComboBox(planObraSocialjComboBox, 0);
    setEditables(true);
  }//GEN-LAST:event_nuevojButtonActionPerformed

  private void aceptarjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_aceptarjButtonActionPerformed
    if (isCreatingPaciente) {
      createNewPaciente();
    } else if (isEditingPaciente) {
      editPaciente();
    } else {

      selectPacienteFromTable();

      if (master.GUID() == User.REGULAR) {
        if (!IsCreatingTurno) {
          master.ShowSlave(master.TurnoGrepPanel());
          return;
        }
        master.TurnoGrepPanel().SetPaciente(pacienteSeleccionado);
        try {
          master.TurnoGrepPanel().UpdatePacienteData();
        } catch (SQLException e) {
          System.out.printf("?secretaria: paciente seleccionado issue\n");
        }
        master.ShowSlave(master.TurnoGrepPanel());

      } else if (master.GUID() == User.MEDICO) {
        master.HistoriaClinicaPanel().SetPaciente(pacienteSeleccionado);
        try {
          master.HistoriaClinicaPanel().UpdateDatosPaciente();
        } catch (SQLException e) {
          System.out.printf("?medico: paciente seleccionado issue\n");
        }
        master.HistoriaClinicaPanel().setCamposEditables(true);
        master.ShowSlave(master.HistoriaClinicaPanel());
      }
    }
  }//GEN-LAST:event_aceptarjButtonActionPerformed

  private void cancelarjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarjButtonActionPerformed
    cancelEverything();
  }//GEN-LAST:event_cancelarjButtonActionPerformed

  private void dnijTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_dnijTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    dnijTextField.selectAll();
  }//GEN-LAST:event_dnijTextFieldFocusGained

  private void nombrejTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_nombrejTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    nombrejTextField.selectAll();
  }//GEN-LAST:event_nombrejTextFieldFocusGained

  private void apellidojTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_apellidojTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    apellidojTextField.selectAll();
  }//GEN-LAST:event_apellidojTextFieldFocusGained

  private void nafiliadojTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_nafiliadojTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    nafiliadojTextField.selectAll();
  }//GEN-LAST:event_nafiliadojTextFieldFocusGained

  private void direccionjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_direccionjTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    direccionjTextField.selectAll();
  }//GEN-LAST:event_direccionjTextFieldFocusGained

  private void telLineajTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_telLineajTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    telLineajTextField.selectAll();
  }//GEN-LAST:event_telLineajTextFieldFocusGained

  private void telCelularjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_telCelularjTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    telCelularjTextField.selectAll();
  }//GEN-LAST:event_telCelularjTextFieldFocusGained

  private void emailjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_emailjTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    emailjTextField.selectAll();
  }//GEN-LAST:event_emailjTextFieldFocusGained

  private void contactoNombrejTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_contactoNombrejTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    contactoNombrejTextField.selectAll();
  }//GEN-LAST:event_contactoNombrejTextFieldFocusGained

  private void contactoApellidojTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_contactoApellidojTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    contactoApellidojTextField.selectAll();
  }//GEN-LAST:event_contactoApellidojTextFieldFocusGained

  private void contactoTelefonojTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_contactoTelefonojTextFieldFocusGained
    if (!isCreatingPaciente) {
      return;
    }
    contactoTelefonojTextField.selectAll();
  }//GEN-LAST:event_contactoTelefonojTextFieldFocusGained

  private void obraSocialjComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_obraSocialjComboBoxActionPerformed
    int selection = obraSocialjComboBox.getSelectedIndex();
    if (selection == -1) {
      return;
    }
    if (osIDs.get(obraSocialjComboBox.getSelectedIndex()) == 0) {
      nafiliadojTextField.setText("0");
      nafiliadojTextField.setEnabled(false);
    } else {
      nafiliadojTextField.setEnabled(true);
    }
    setUpPlanComboBox(planObraSocialjComboBox, osIDs.get(selection));
  }//GEN-LAST:event_obraSocialjComboBoxActionPerformed

  private void modificarjButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_modificarjButtonActionPerformed
    if (buscarjTable.getSelectedRow() == -1) {
      return;
    }
    isEditingPaciente = true;
    nuevojButton.setEnabled(false);
    modificarjButton.setEnabled(false);
    buscarjTable.setEnabled(false);
    buscarjTextField.setEnabled(false);
    setEditables(true);
  }//GEN-LAST:event_modificarjButtonActionPerformed

  private void buscarjTextFieldFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_buscarjTextFieldFocusGained
    buscarjTextField.selectAll();
  }//GEN-LAST:event_buscarjTextFieldFocusGained

  private void buscarjTableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_buscarjTableKeyReleased
    buscarjTableMouseClicked(null);
  }//GEN-LAST:event_buscarjTableKeyReleased

  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JButton aceptarjButton;
  private javax.swing.JLabel apellidojLabel;
  private javax.swing.JTextField apellidojTextField;
  private javax.swing.JLabel buscarjLabel;
  private javax.swing.JScrollPane buscarjScrollPane;
  private javax.swing.JTable buscarjTable;
  private javax.swing.JTextField buscarjTextField;
  private javax.swing.JButton cancelarjButton;
  private javax.swing.JLabel contactoApellidojLabel;
  private javax.swing.JTextField contactoApellidojTextField;
  private javax.swing.JPanel contactoEmergenciasjPanel;
  private javax.swing.JLabel contactoNombrejLabel;
  private javax.swing.JTextField contactoNombrejTextField;
  private javax.swing.JLabel contactoTelefonojLabel;
  private javax.swing.JTextField contactoTelefonojTextField;
  private javax.swing.JLabel direccionjLabel;
  private javax.swing.JTextField direccionjTextField;
  private javax.swing.JLabel dnijLabel;
  private javax.swing.JTextField dnijTextField;
  private javax.swing.JLabel emailjLabel;
  private javax.swing.JTextField emailjTextField;
  private kalendar.calendar.JDateChooser fechaNacjDateChooser;
  private javax.swing.JLabel fechaNacjLabel;
  private javax.swing.JButton modificarjButton;
  private javax.swing.JLabel nafiliadojLabel;
  private javax.swing.JTextField nafiliadojTextField;
  private javax.swing.JLabel nombrejLabel;
  private javax.swing.JTextField nombrejTextField;
  private javax.swing.JButton nuevojButton;
  private javax.swing.JComboBox obraSocialjComboBox;
  private javax.swing.JLabel obraSocialjLabel;
  private javax.swing.JLabel pacientejLabel;
  private javax.swing.JComboBox planObraSocialjComboBox;
  private javax.swing.JLabel telCelularjLabel;
  private javax.swing.JTextField telCelularjTextField;
  private javax.swing.JLabel telLineajLabel;
  private javax.swing.JTextField telLineajTextField;
  // End of variables declaration//GEN-END:variables
}
